package javax.xianfeng.drools.util;

import java.util.Objects;

import org.kie.api.KieBase;
import org.kie.api.io.ResourceType;
import org.kie.api.runtime.KieSession;
import org.kie.api.runtime.StatelessKieSession;
import org.kie.internal.utils.KieHelper;
import org.springframework.util.StopWatch;

import lombok.extern.slf4j.Slf4j;

/**
 * @since 2020/04/09 22:18:32
 */
@Slf4j
public final class DroolsUtils {

	private DroolsUtils() {
		super();
	}

	/**
	 * 创建KieHelper
	 * 
	 * @param drlContents
	 * @return
	 * @since 2020/04/09 21:55:06
	 */
	public static KieHelper getKieHelper(String... drlContents) {
		KieHelper kieHelper = new KieHelper();
		for (String drlContent : drlContents) {
			kieHelper.addContent(drlContent, ResourceType.DRL);
		}
		return kieHelper;
	}

	/**
	 * 创建KieSession
	 * 
	 * @param kieHelper
	 * @return
	 * @since 2020/04/09 22:24:10
	 */
	public static KieSession createSession(KieHelper kieHelper) {
		return kieHelper.build().newKieSession();
	}
	
	/**
	 * 创建StatelessKieSession
	 * @param kieHelper
	 * @return
	 * @since 2020/04/22 17:24:28
	 */
	public static StatelessKieSession createStatelessSession(KieHelper kieHelper) {
		StopWatch stopWatch = new StopWatch();
		stopWatch.start();
		
		KieBase kieBase = kieHelper.build();
		
		stopWatch.stop();
		log.info("drools耗时1: {} ms", stopWatch.getLastTaskTimeMillis());
		stopWatch.start();
		
		StatelessKieSession kieSession =kieBase.newStatelessKieSession(); 
		
		stopWatch.stop();
		log.info("drools耗时2: {} ms", stopWatch.getLastTaskTimeMillis());
		stopWatch.start();

		log.info("drools总耗时: {} ms", stopWatch.getTotalTimeMillis());
		
		return kieSession;
	}

	/**
	 * 关闭KieSession
	 * 
	 * @param kieSession
	 * @since 2020/04/09 22:21:13
	 */
	public static void closeSession(KieSession kieSession) {
		if (Objects.nonNull(kieSession)) {
			kieSession.dispose();
		}
	}

}
